package com.sendpo.zjx.sendpo.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.MerchatsActiveDomain;
import com.sendpo.zjx.sendpo.domain.MerchatsActiveInfoDomain;
import com.sendpo.zjx.sendpo.domain.MerchatsmianDynimcDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.KeyBoardUtils;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;
import org.raphets.roundimageview.RoundImageView;
import org.xutils.common.Callback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by Administrator on 2017/8/18.
 */

public class MerchatsActiveInfoActvitiy extends AppCompatActivity {


    @BindView(R.id.share_bt)
    RelativeLayout shareBt;
    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.send_bt)
    Button sendBt;
    @BindView(R.id.editer_iv)
    ImageView editerIv;
    @BindView(R.id.content_edit)
    EditText contentEdit;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.head_icon)
    CircleImageView headIcon;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.datetime)
    TextView datetime;
    @BindView(R.id.location)
    TextView location;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.text)
    WebView text;
    @BindView(R.id.imgs)
    LinearLayout imgs;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.queryall_guest)
    RelativeLayout queryallGuest;

    BottomDialog bottomDialog;
    public Tencent tencent = null;
    public int id = 0;
    private RecylcerAdaper adpter;
    private int currentlastitem=0;
    private LinearLayoutManager lm=null;
    private int pagenow=1;
    private boolean lastloading=false;
    private  MerchatsmianDynimcDomain.DataBean dataBean=null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_merchatsactiveinfo);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
        dataBean = (MerchatsmianDynimcDomain.DataBean) getIntent().getSerializableExtra("data");
         if(dataBean!=null){
             id=dataBean.getMerchantsDyId();
             initInfo(id+"");
          pagenow=1;
         query(pagenow,id);
               addWatch(id+"");
         }
    }

    private void initComponent() {
        lm = new LinearLayoutManager(this, OrientationHelper.VERTICAL, false) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        recyclerview.setLayoutManager(lm);


        initShare();
    }

    public void initShare() {
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View qqsapce = v.findViewById(R.id.qqspace_bt);
                qqsapce.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        shareToQzone();
                    }
                });
                View qq_bt = v.findViewById(R.id.qq_bt);
                qq_bt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onClickQQShare();
                    }
                });

                View exit = v.findViewById(R.id.closebt);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.layout_dialog_share);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");
        tencent = Tencent.createInstance(HttpUrl.QQ_KEY, getApplicationContext());

    }

    @OnClick(value = {R.id.backbt, R.id.share_bt, R.id.send_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;

            case R.id.share_bt:
                bottomDialog.show();
                break;
            case R.id.send_bt:
                List<User> userList= Xutils.queryAll(getApplication(),User.class);
                if(userList==null||userList.size()==0){
                    Tools.redirectActivity(MerchatsActiveInfoActvitiy.this,LoginActivity.class);
                    return;
                }
                if(TextUtils.isEmpty(contentEdit.getText().toString().trim())){
                    Toast.makeText(getApplicationContext(),"评论不能空",Toast.LENGTH_SHORT).show();
                    return;
                }
                addGuest(id+"",userList.get(0).getUserId()+"",contentEdit.getText().toString().trim());
                contentEdit.getText().clear();
                KeyBoardUtils.closeKeybord(contentEdit,this);
                break;
        }
    }

    private class TextClick extends ClickableSpan {
        @Override
        public void onClick(View widget) {
            //在此处理点击事件
            Toast.makeText(getApplicationContext(), "圆环之理赐予幸福", Toast.LENGTH_LONG).show();
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(getResources().getColor(R.color.default_blue));

        }
    }


    //QQ腾讯好友分享
    private void onClickQQShare() {

        Bundle data = new Bundle();
        data.putString(QQShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        data.putString(QQShare.SHARE_TO_QQ_TITLE, "产品标题");
        data.putString(QQShare.SHARE_TO_QQ_SUMMARY, "产品描述");
        data.putString(QQShare.SHARE_TO_QQ_TARGET_URL, "http://www.baidu.com");
        data.putString(QQShare.SHARE_TO_QQ_IMAGE_URL,
                "http://images.3158.cn/data/attachment/tougao/article/2015/12/17/df0b92921cb9fa8bb4f82c18ad1e08ba.jpg");
        data.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        data.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        tencent.shareToQQ(this, data, new QQShareUiListener());
    }

    //QQ分享监听
    private class QQShareUiListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
            System.out.println("********" + o.toString());

        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(getApplicationContext().getApplicationContext(), uiError.errorDetail, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {

        }
    }


    //QQ腾讯分享空间
    private void shareToQzone() {
//分享类型
        Bundle params = new Bundle();
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, getResources().getString(R.string.app_name));
        params.putString(QQShare.SHARE_TO_QQ_TITLE, "产品标题");
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, "产品描述");
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, "http://wapi.jiechennuo.com/wifijz.apk");
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        ArrayList<String> strings = new ArrayList<String>();
        strings.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491909596292&di=8d177470e12744ff9eba0f7f55a89c78&imgtype=0&src=http%3A%2F%2Fwww.pp3.cn%2Fuploads%2F201611%2F2016120301.jpg");
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, strings);
        tencent.shareToQzone(this, params, new QQShareUiListener());
    }





    public  void addGuest(String merchantsDyId,String userId,String CommentText){
        Map<String,String > map=new HashMap<>();
        map.put("userId",""+userId);
        map.put("merchantsDyId",""+merchantsDyId);
        map.put("CommentText",CommentText);
        Xutils.POST(HttpUrl.mercommentAdd, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")){
                        case HttpCode.SUCCESS:

                      pagenow=1;
                      query(pagenow,id);
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(getApplicationContext(),"请稍后重试",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void addWatch(String dynamicId){
        Map<String,String> map=new HashMap<>();
        map.put("merchantsDyId",""+dynamicId);
        Xutils.POST(HttpUrl.merchantdynmicbusinessCountAdd, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    public class RecylcerAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        public List<MerchatsActiveDomain.DataBean> dataBeen;
        public LayoutInflater inflater;
        public RecylcerAdaper(List<MerchatsActiveDomain.DataBean> dataBeen, Context context) {
            inflater = LayoutInflater.from(context);
            this.dataBeen = dataBeen;
        }
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder ih = null;
            ih = new IndexHoler(inflater.inflate(R.layout.layout_userguest_listitem, parent, false));
            return ih;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
            final IndexHoler ih = (IndexHoler) holder;
            final MerchatsActiveDomain.DataBean dataBean=dataBeen.get(position);
            System.out.println("****************"+dataBean.getUserAvatarpath());
            ih.cir_icon.setImageResource(R.drawable.nim_avatar_default);
            Glide.with(MerchatsActiveInfoActvitiy.this)
                    .load(dataBean.getUserAvatarpath()+"")
                    .          asBitmap().
                    placeholder(R.drawable.nim_avatar_default)
                    .animate(R.anim.fade_in)
                    .centerCrop()
                    .into(new SimpleTarget<Bitmap>() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                            ih.cir_icon.setImageBitmap(resource);
                        }
                    });
            ih.cir_icon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Map<String,Object> map=new HashMap<>();
                    map.put("id",dataBean.getUserId());
                    Tools.redirectActivity(MerchatsActiveInfoActvitiy.this, UserPersonCenterActivity.class,map);
                }
            });
            ih.name.setText(""+dataBean.getUserName());
            if(!TextUtils.isEmpty(dataBean.getCommentsCreatetime())){
                ih.dateitme.setText(new SimpleDateFormat("yyyy年MM月dd日").format(Tools.getStringtoDate(dataBean.getCommentsCreatetime(),"yyyy-MM-dd HH:mm:ss"))+"");
            }
            ih.content.setText(""+dataBean.getCommentText());
        }

        @Override
        public int getItemCount() {
            return dataBeen.size();
        }

        public class IndexHoler extends RecyclerView.ViewHolder {
            public View rootView;
            public CircleImageView cir_icon;
            public TextView name;
            public TextView dateitme;
            public TextView content;
            public IndexHoler(View itemView) {
                super(itemView);
                rootView = itemView;
                cir_icon=itemView.findViewById(R.id.cir_icon);
                name=itemView.findViewById(R.id.name);
                dateitme=itemView.findViewById(R.id.dateitme);
                content=itemView.findViewById(R.id.content);
            }
        }

        public void initRefresh(List<MerchatsActiveDomain.DataBean> domains) {
            this.dataBeen.removeAll(this.dataBeen);
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void initAppend(List<MerchatsActiveDomain.DataBean> domains) {
            this.dataBeen.addAll(domains);
            notifyDataSetChanged();
        }

        public void delete(int position) {
            this.dataBeen.remove(position);
            notifyDataSetChanged();
        }

    }

    public void query(int pagenow, final int dynamicId) {
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsDyId", dynamicId + "");
        Xutils.POST(HttpUrl.mercommentQuery, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                MerchatsActiveDomain domain= gson.fromJson(result, MerchatsActiveDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), MerchatsActiveInfoActvitiy.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (MerchatsActiveInfoActvitiy.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                MerchatsActiveInfoActvitiy.this.pagenow++;
                                                append(MerchatsActiveInfoActvitiy.this.pagenow, dynamicId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initRefresh(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void append(int pagenow, final int dynamicId) {
        lastloading = true;
        Map<String, String> map = new HashMap<>();
        map.put("pagenow", pagenow + "");
        map.put("merchantsDyId", dynamicId + "");
        Xutils.POST(HttpUrl.mercommentQuery, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                lastloading = false;
                Gson gson = new Gson();
                MerchatsActiveDomain domain = gson.fromJson(result, MerchatsActiveDomain.class);
                switch (domain.getState()) {
                    case HttpCode.SUCCESS:
                        if (domain.getData() != null && domain.getData().size() != 0) {
                            if (adpter == null) {
                                recyclerview.setAdapter(adpter = new RecylcerAdaper(domain.getData(), MerchatsActiveInfoActvitiy.this));
                                recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
                                    @Override
                                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                                        super.onScrollStateChanged(recyclerView, newState);
                                        if (currentlastitem == lm.getItemCount() - 1 && newState == RecyclerView.SCROLL_STATE_IDLE) {
                                            if (MerchatsActiveInfoActvitiy.this.pagenow == 1 && adpter.dataBeen.size() >= 10 && lastloading == false) {
                                                MerchatsActiveInfoActvitiy.this.pagenow++;
                                                append(MerchatsActiveInfoActvitiy.this.pagenow, dynamicId);
                                            }
                                        }
                                    }

                                    @Override
                                    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                                        super.onScrolled(recyclerView, dx, dy);
                                        currentlastitem = lm.findLastVisibleItemPosition();
                                    }
                                });
                            } else {
                                adpter.initAppend(domain.getData());
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                lastloading = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    public void initInfo(String dynamicId ){
        Map<String,String> map=new HashMap<>();
        map.put("merchantsDyId",""+dynamicId);
        Xutils.POST(HttpUrl.merchantdynmicbusinessbydynamicid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
               MerchatsActiveInfoDomain domain=gson.fromJson(result,MerchatsActiveInfoDomain.class);
                 switch (domain.getState()){
                     case HttpCode.SUCCESS:
                         MerchatsActiveInfoDomain.DataBean dataBean=domain.getData();
                          if(TextUtils.isEmpty(dataBean.getUserAvatarpath()+"")){
                              Glide.with(MerchatsActiveInfoActvitiy.this)
                                      .load(dataBean.getUserAvatarpath()+"")
                                      .asBitmap()
                                      .animate(R.anim.fade_in)
                                      .placeholder(R.drawable.nim_avatar_default)
                                      .into(new SimpleTarget<Bitmap>() {
                                          @Override
                                          public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                              headIcon.setImageBitmap(resource);
                                          }
                                      });
                          }else{
                              Glide.with(MerchatsActiveInfoActvitiy.this)
                                      .load(dataBean.getMerchantsAvatarpath()+"")
                                      .asBitmap()
                                      .animate(R.anim.fade_in)
                                      .placeholder(R.drawable.nim_avatar_default)
                                      .into(new SimpleTarget<Bitmap>() {
                                          @Override
                                          public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                              headIcon.setImageBitmap(resource);
                                          }
                                      });
                          }
                         name.setText(dataBean.getMerchantsName());
                         datetime.setText(""+dataBean.getMerchantsCreatedate());
                         location.setText(""+dataBean.getMerchantsArea());
                         title.setText(""+dataBean.getMerchantsDyComment());
                      //   text.loadDataWithBaseURL("",""+dataBean.getUserFriendscircleText(),"text/html","utf-8","");
                         if(dataBean.getMerchantsDyImgsPath()!=null&&dataBean.getMerchantsDyImgsPath().size()!=0){
                             for(int i=0;i<dataBean.getMerchantsDyImgsPath().size();i++){
                                 ImageView iv=new ImageView(MerchatsActiveInfoActvitiy.this);
                                 iv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
                                 Glide.with(MerchatsActiveInfoActvitiy.this)
                                         .load(""+dataBean.getMerchantsDyImgsPath().get(i))
                                         .asBitmap()
                                         .placeholder(getResources().getColor(R.color.default_lightgray))
                                         .animate(R.anim.fade_in)
                                         .into(iv);
                                 imgs.addView(iv);
                             }
                         }
                         break;
                 }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}
